package com.py.chat.server;

import com.google.protobuf.MessageLite;

import com.py.chat.bean.Gloable;
import com.py.chat.bean.Session;
import com.py.chat.proto.ProtoMapper.ProtoMapperEnum;
import com.py.chat.proto.ProtoMapper;
import com.py.chat.proto.ChatProbuf.ChatLog;
import com.py.chat.proto.ChatProbuf.STCChatRet;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;

public class ServerHandler extends SimpleChannelInboundHandler<MessageLite> {
	
    @Override
    //客户端连接
    public void channelActive(final ChannelHandlerContext ctx) {
    	System.err.println("有新客户端连接");
    	Session client = new Session(ctx.channel());
    	ctx.channel().attr(ServerAttributeKey.SessionKey).set(client);
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, MessageLite msg) throws Exception {
    	System.err.println("msg"+msg.getClass());
    	ProtoMapperEnum e = ProtoMapper.getProtoMapperEnum(msg.getClass());
    	e.handle.session = ctx.channel().attr(ServerAttributeKey.SessionKey).get();
    	MessageLite retMsg = e.handle.handle0(msg);
    	if (retMsg != null) {
			ctx.writeAndFlush(retMsg);
		}
    }
    
    @Override
    // 客户端关闭
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	Session session = ctx.channel().attr(ServerAttributeKey.SessionKey).get();
    	if (session.user != null) {
    		ChatServer.broadcast(STCChatRet.newBuilder().setStatus(0).setChatLog(ChatLog.newBuilder().setMsg(session.user.getName()+"下线了")).build(), session.user);
    		session.user.offline();
    		Gloable.sessionMap.remove(session.user.getId());
		}
    	super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

